package com.spring.core.io.support;

/**
 * Copyright (c) 2018-2023 ThunderSoft
 * All Rights Reserved by Thunder Software Technology Co., Ltd and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with ThunderSoft in writing by applicable law.
 */

import com.spring.core.SpringProperties;
import com.spring.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author liyuncong
 * @version 1.0
 * @file PropertiesLoaderUtils
 * @brief PropertiesLoaderUtils
 * @details PropertiesLoaderUtils
 * @date 2023-01-13
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2023-01-13                  liyuncong          Created
 */
public abstract class PropertiesLoaderUtils {
    private static final String XML_FILE_EXTENSION = ".xml";

    private static final boolean shouldIgnoreXml = SpringProperties.getFlag("spring.xml.ignore");

    public static Properties loadProperties(Resource resource) throws IOException {
        Properties properties = new Properties();
        fillProperties(properties, resource);
        return properties;
    }

    public static void fillProperties(Properties properties, Resource resource) throws IOException {
        try (InputStream inputStream = resource.getInputStream()) {
            final String fileName = resource.getFileName();
            if (fileName != null && fileName.endsWith(XML_FILE_EXTENSION)) {
                if (shouldIgnoreXml) {
                    throw new UnsupportedOperationException("XML support disabled");
                }
                properties.loadFromXML(inputStream);
            } else {
                properties.load(inputStream);
            }
        }
    }

}
